﻿/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.ball.views.obstacles
{
	import com.puny.ball.utils.Vector2D;
	import com.puny.ball.utils.handlers.IMovingHandler;
	import com.puny.mvc.helpers.FrameHelper;
	import com.puny.mvc.helpers.IHelper;
	
	import flash.events.Event;
	
	public class MovingCircleObstacle extends CirculerShapeObstacle
	{
		
		private const _a:Vector2D = new Vector2D();
		
		private var _random:Boolean = true;
		private var _helper:IHelper;
		private var _motion:IMovingHandler;
		public function MovingCircleObstacle()
		{
			super();
		}
		
		protected function set motion(value:IMovingHandler):void {
			_motion = value;
		}
		
		override protected function addedStageHandler(event:Event):void {
			super.addedStageHandler(event);

			_motion.motionDefinition(x,y);
			
			startEnterFrame();
		}
				
		override protected function removedStageHandler(event:Event):void {
			super.removedStageHandler(event);
			if (_helper != null) {
				_helper.cancel();
			}
		}

		private function startEnterFrame():void {
			_helper = FrameHelper.setup(this, _motion.initialize, loop, startEnterFrame);
		}

		private function loop():Boolean {
			var ret:Boolean = _motion.nextPosition();			

			x = _motion.org.x;
			y = _motion.org.y;

			drawDebugShape();

			return ret;
		}
		
		override public function collision(org:Vector2D, dir:Vector2D):Boolean {
			_a.x = dir.x - _motion.v.x;
			_a.y = dir.y - _motion.v.y;
			if (super.collision(org, _a)) {
				if ((newPos.x - mirroredPos.x)*_motion.v.x < 0) {
					newPos.x -= _motion.noisedVx(_a.x == 0);
					newPos.y -= _motion.noisedVy(_a.y == 0);
				} else {
					newPos.x += _motion.noisedVx(_a.x == 0);
					newPos.y += _motion.noisedVy(_a.y == 0);
				}
				return true;
			}
			return false;
		}

		override public function set x(value:Number):void {
			super.x = value;
			center.x = x;
			cpa.center.x = x;
		}
		
		override public function set y(value:Number):void {
			super.y = value;
			center.y = y;
			cpa.center.y = y;
		}
		
		public function debugInfo():String {
			return _motion.debug();
		}
		public function resume(dir:String, pos:int):void {
			_motion.resume(dir, pos);
		}
	}
}